package com.keqiang.chart.impl.axis.impl.bar.horizontal

import android.graphics.RectF
import android.view.MotionEvent
import com.keqiang.chart.impl.axis.BaseTouchHandler
import com.keqiang.chart.impl.axis.impl.bar.BarEntity
import kotlin.math.abs

/**
 * 处理柱状图的触摸
 *
 * @author Created by wanggaowan on 2022/7/29 14:06
 */
open class BarHorizontalTouchHandler(chart: BarChartHorizontal) : BaseTouchHandler<BarChartHorizontal, List<BarEntity>>(chart) {

    override fun onScroll(e1: MotionEvent?, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean {
        if (!moveChosenEnable) {
            return false
        }

        if (abs(distanceY) < abs(distanceX)) {
            if (!captureTouchEvent) {
                chart.view.parent.requestDisallowInterceptTouchEvent(false)
            }
            return false
        }

        captureTouchEvent = true
        return findTouchInRange(e2, true)
    }

    override fun getTouchData(x: Float, y: Float, isMove: Boolean): List<BarEntity>? {
        if (chart.data == null) {
            return null
        }

        val inRangePoint = mutableListOf<BarEntity>()
        chart.data?.groups?.forEach {
            for (value in it.values) {
                if (isTouchInRectF(x, y, value.drawRectF, isMove)) {
                    inRangePoint.add(value)
                    break
                }
            }
        }

        return if (inRangePoint.isEmpty()) null else inRangePoint
    }

    /**
     * 点击是否在指定范围内容，[isXAllValid]表示是否x轴全局域触摸有效，如果为true，那么则无需判断手指x轴坐标
     */
    private fun isTouchInRectF(x: Float, y: Float, rectF: RectF, isXAllValid: Boolean = false): Boolean {
        if (y >= rectF.top && y <= rectF.bottom) {
            if (isXAllValid) {
                return true
            }

            return x >= rectF.left && x <= rectF.right
        }

        return false
    }
}
